package com.qf.main.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.main.login.common.qo.SysRoleQo;
import com.qf.main.login.common.vo.SysRoleVo;
import com.qf.main.login.entity.RoleOperationPermission;
import com.qf.main.login.entity.SysRole;
import com.qf.main.login.mapper.RoleOperationPermissionMapper;
import com.qf.main.login.mapper.SysRoleMapper;
import com.qf.main.login.mapper.SysRolePermissionMapper;
import com.qf.main.login.service.RoleService;
import com.qf.main.login.utils.CommonBeanutils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author chengqiang
 * @Create 2024-01-19-10:59
 * @Description:
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private SysRolePermissionMapper sysRolePermissionMapper;
    @Resource
    private RoleOperationPermissionMapper roleOperationPermissionMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Override
    public List<SysRoleVo> queryRoles(Integer userId) {
        sysRolePermissionMapper.selectRolesAndPermission(userId);
        return sysRolePermissionMapper.selectRolesAndPermission(userId);
    }


    // 添加角色
    @Override
    @Transactional
    public Integer insertRole(SysRoleQo sysRoleQo) {
        SysRole sysRole = CommonBeanutils.convertTo(sysRoleQo, SysRole::new);
        sysRoleMapper.insertGeneratedKeys(sysRole);
        List<Integer> sysPermissionIdList = sysRoleQo.getSysPermissionIdList();

        // 添加角色和权限的练习
        for (Integer sysPermissionId : sysPermissionIdList) {
            RoleOperationPermission roleOperationPermission = RoleOperationPermission.builder().roleId(sysRole.getId()).permissionId(sysPermissionId).build();
            roleOperationPermissionMapper.insert(roleOperationPermission);
        }
        return 1;
    }

    @Override
    public List<SysRoleVo> queryRoles() {
        QueryWrapper<SysRole> qw = new QueryWrapper<>();
        List<SysRole> sysRoles = sysRoleMapper.selectList(qw);

        // po转vo
        return CommonBeanutils.convertListTo(sysRoles, SysRoleVo::new);
    }


}
